﻿using System.Collections.Generic;
using System.ComponentModel;

namespace Sidvall.Configuration
{
    public abstract class SettingsBase : ISettings, INotifyPropertyChanged
    {
        #region Public Members

        public event PropertyChangedEventHandler PropertyChanged;

        #region GetSetting

        public virtual object GetSetting(string propertyName)
        {
            var propertyValue = GetSetting<object>(propertyName);
            return propertyValue;
        }
        protected virtual T GetSetting<T>(string propertyName)
        {
            if (this.Settings.ContainsKey(propertyName))
                return (T)this.Settings[propertyName];
            return default(T);
        }

        #endregion
        #region SetSetting

        public virtual bool SetSetting(string propertyName, object value)
        {
            return SetSetting<object>(propertyName, value);
        }
        protected virtual bool SetSetting<T>(string propertyName, T value)
        {
            if (this.Settings.ContainsKey(propertyName))
            {
                var currentValue = (T)this.Settings[propertyName];
                if (EqualityComparer<T>.Default.Equals(currentValue, value))
                    return false;
            }

            this.Settings[propertyName] = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion

        #region OnPropertyChanged

        protected void OnPropertyChanged(string propertyName)
        {
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged.Invoke(this, args);
        }

        #endregion

        #endregion
        #region Private Members

        #region Settings

        private System.Lazy<System.Collections.Generic.Dictionary<string, object>> _Settings = new System.Lazy<System.Collections.Generic.Dictionary<string, object>>();
        private System.Collections.Generic.Dictionary<string, object> Settings
        {
            get
            {
                return _Settings.Value;
            }
        }

        #endregion

        #endregion
    }
}
